package com.yzkj.siot.aspect;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentParser;
import cn.hutool.json.JSONUtil;
import com.yzkj.siot.annotation.WebLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
@Profile({"local", "test"})
public class WebLogPrintAspect {

    @Pointcut("@annotation(com.yzkj.siot.annotation.WebLog)")
    public void webLog() {
    }

    /**
     * 在切点之前执行
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();

        //获取请求头中的User-Agent
        UserAgent userAgent = UserAgentParser.parse(request.getHeader("User-Agent"));

        // 获取注解中的参数值
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        WebLog webLogAnnotation = method.getAnnotation(WebLog.class);

        // 打印请求相关参数
        log.debug("========================================== Start ==========================================");
        // 打印请求 url
        log.debug("URL            : {}", request.getRequestURL().toString());
        // 打印 Http method
        log.debug("HTTP Method    : {}", request.getMethod());
        // 打印接口类型
        log.debug("Api Type       : {}", webLogAnnotation.type().toString());
        // 打印调用 controller 的全路径以及执行方法
        log.debug("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName());
        // 打印请求的 IP
        log.debug("IP             : {}", request.getRemoteAddr());
        // 打印请求入参
        log.debug("Request Args   : {}", JSONUtil.toJsonStr(joinPoint.getArgs()));
        // 打印浏览器信息
        log.debug("Browser        : {} {}", userAgent.getBrowser().getName(), userAgent.getVersion());
        // 打印操作系统信息
        log.debug("Os             : {} {}", userAgent.getOs().getName(), userAgent.getOsVersion());
        // 打印内核引擎信息
        log.debug("Engine         : {} {}", userAgent.getEngine().getName(), userAgent.getEngineVersion());
    }

    /**
     * 环绕
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        // 打印出参
        log.debug("Response Args  : {}", JSONUtil.toJsonStr(result));
        // 执行耗时
        log.debug("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
        log.debug("=========================================== End ===========================================");
        return result;
    }
}